﻿using System;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Views.Animations;
using Android.Widget;
using Koush;
using Xamarin.ActionbarSherlockBinding.App;
using Cinemacenter.Shared;

namespace Cinemacenter.Droid
{
	public class MovieDetailsFragment : SherlockFragment
	{
		Movie movie;
		Xamarin.ActionbarSherlockBinding.Widget.ShareActionProvider mShareActionProvider;

		public override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			var movieId = Arguments.GetInt ("movieId");
			movie = DBHelper.GetMovie (movieId);
			HasOptionsMenu = true;
		}

		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			View detailsView = inflater.Inflate (Resource.Layout.MovieDetailsView, container, false);
			var tvTitle = detailsView.FindViewById<TextView> (Resource.Id.tvMovieName);
			var tvMovieType = detailsView.FindViewById<TextView> (Resource.Id.tvMovieType);
			var splited = movie.Name.Split (new []{ " - " }, StringSplitOptions.RemoveEmptyEntries);
			var ivPoster = detailsView.FindViewById<ImageView> (Resource.Id.ivPoster);
			var btnTrailer = detailsView.FindViewById<Button> (Resource.Id.btnTrailer);
			if (!string.IsNullOrEmpty (movie.TrailerUrl)) {
				Animation animScale = AnimationUtils.LoadAnimation (Activity, Resource.Animation.scale);
				btnTrailer.StartAnimation (animScale);
				btnTrailer.Click += delegate {
					var browserIntent = new Intent (Intent.ActionView, Android.Net.Uri.Parse (movie.TrailerUrl));
					Activity.StartActivity (browserIntent);
				};
			} else {
				btnTrailer.Visibility = ViewStates.Gone;
			}

			UrlImageViewHelper.SetUrlDrawable (ivPoster, movie.PosterUrl, Resource.Drawable.ic_fallback);
			tvTitle.Text = splited [0];
			tvMovieType.Text = splited [1];
			return detailsView;
		}

		Intent getDefaultShareIntent ()
		{
			var intent = new Intent (Intent.ActionSend);
			intent.SetType ("text/plain");
			intent.PutExtra (Intent.ExtraSubject, Resource.String.app_name);
			intent.PutExtra (Intent.ExtraText, movie.Name + " en Cinemacenter. Más info => " + movie.Link);
			return intent;
		}

		public override void OnCreateOptionsMenu (Xamarin.ActionbarSherlockBinding.Views.IMenu menu, Xamarin.ActionbarSherlockBinding.Views.MenuInflater inflater)
		{
			inflater.Inflate (Resource.Menu.activity_details, menu);
			mShareActionProvider = (Xamarin.ActionbarSherlockBinding.Widget.ShareActionProvider)menu.FindItem (Resource.Id.menu_share_app).ActionProvider;
			Intent intent = getDefaultShareIntent ();
			if (intent != null)
				mShareActionProvider.SetShareIntent (intent);
			base.OnCreateOptionsMenu (menu, inflater);
		}

	}
}